package io.jft.doll.weidget

import android.content.Context
import android.os.CountDownTimer
import android.support.v7.widget.AppCompatImageButton
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View

/**
 * Created by G on 2017/12/31 0031.
 */
class GameControlButton : AppCompatImageButton {
    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    var pressIntervalListener: PressIntervalListener? = null
    var touchDownListener: PressDownListener? = null
    private val timer = object : CountDownTimer(Long.MAX_VALUE, 200L) {
        override fun onFinish() {
        }

        override fun onTick(p0: Long) {
            pressIntervalListener?.onTick(this@GameControlButton)
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        var result = super.onTouchEvent(event)

        pressIntervalListener?.also {
            result = true
            when (event?.action) {
                MotionEvent.ACTION_DOWN -> {
                    pressIntervalListener?.onTick(this)
                    touchDownListener?.onTouchDown(this)
                    doCallBack()
                }
                MotionEvent.ACTION_UP -> doUpCallBack()
                MotionEvent.ACTION_CANCEL -> doUpCallBack()
            }
        }
        return result
    }


    private fun doCallBack() {
        timer.start()
    }

    private fun doUpCallBack() {
        timer.cancel()
    }

    fun setOnPressIntervalListener(exec: PressIntervalListener?) {
        pressIntervalListener = exec
    }

    fun setOnTouchStartListener(exec: PressDownListener?) {
        touchDownListener = exec
    }

    interface PressIntervalListener {
        fun onTick(view: View)
    }

    interface PressDownListener {
        fun onTouchDown(view: View)
    }
}